package factory

import (
	"time"

	"github.com/pkg/errors"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/reviewd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd"
)

var (
	// ErrNotSupportType 不支持的审核类型
	ErrNotSupportType = errors.New("不支持的审核类型")
	// ErrNotFound 没有找到资源
	ErrNotFound = errors.New("没有找到资源")
)

func (f factory) ReviewOK(ctx ddd.Context, targetType int, targetID, reason, reviewer string) error {

	switch targetType {
	case reviewd.TargetTypeInfo:
		// 信息 审核
		return reviewInfo(ctx, f, reviewd.ReviewDesc{
			TargetType: targetType,
			TargetID:   targetID,
			Reviewer:   reviewer,
			Reason:     reason,
			Result:     true,
			ReviewTime: time.Now(),
		})
	case reviewd.TargetTypeReply:
		// 评论审核
	default:
		return ErrNotSupportType
	}
	return nil
}
func (f factory) ReviewNo(ctx ddd.Context, targetType int, targetID, reason, reviewer string) error {

	switch targetType {
	case reviewd.TargetTypeInfo:
		// 信息 审核
		return reviewInfo(ctx, f, reviewd.ReviewDesc{
			TargetType: targetType,
			TargetID:   targetID,
			Reviewer:   reviewer,
			Reason:     reason,
			Result:     false,
			ReviewTime: time.Now(),
		})
	case reviewd.TargetTypeReply:
		// 评论审核
		return ErrNotSupportType
	default:
		return ErrNotSupportType
	}
	//return nil
}

func reviewInfo(ctx ddd.Context, f factory, desc reviewd.ReviewDesc) (err error) {
	// 获取信息
	if i, err := f.iar.GetInfo(ctx, desc.TargetID); err != nil {
		return err
	} else if i == nil {
		return ErrNotFound
	} else {
		var id string

		if id, err = f.reviewar.AddReview(ctx, desc); err != nil {
			return errors.Wrapf(err, "创建审核信息失败:%v", desc)
		}
		if desc.Result {
			if err = i.CheckOK(ctx, desc.Reason); err != nil {
				f.reviewar.DeleteReview(ctx, id)
				return errors.Wrapf(err, "修改信息(%v)的审核状态失败:%v", desc.TargetID, desc.Reason)
			}
			return nil
		}
		if err = i.CheckNo(ctx, desc.Reason); err != nil {
			f.reviewar.DeleteReview(ctx, id)
			return errors.Wrapf(err, "修改信息(%v)的审核状态失败:%v", desc.TargetID, desc.Reason)
		}
		return nil
	}

}
